import { useState, useEffect } from "react";
import {
  Row,
  Col,
  Tabs,
  Carousel,
  Card,
  Input,
  Button,
  List,
  Badge,
} from "antd";
import InfiniteScroll from "react-infinite-scroll-component";
import { useNavigate } from "react-router-dom";

import fileImg from "@/assets/file.png";
import firImg from "@/assets/fri.png";
import movImg from "@/assets/mov.png";
import muImg from "@/assets/mu.png";
import picImg from "@/assets/pic.png";
import service from "@/http/request";

const { TabPane } = Tabs;

const sectionMap = {
  图书: "BOOK",
  交友: "SOCIAL",
  软件: "SOFTWARE",
  音乐: "MUSIC",
  影视: "MOVIE",
};

const QuestionList = () => {
  const carouselImages = [muImg, movImg, fileImg, firImg, picImg];
  const [carouselPosts, setCarouselPosts] = useState([]);

  const [activeModule, setActiveModule] = useState("图书");
  const [posts, setPosts] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [pageNum, setPageNum] = useState(1);
  const pageSize = 9;
  const [searchKeyword,setSearchKeyword] = useState("");
  const [isSearching,setIsSearching] = useState(false)
  const navigate = useNavigate();

  useEffect(() => {
    service.get("/forum2/posts/recommend").then((res) => {
      const data = res;
      const posts = Object.keys(data).map((key) => data[key]);
      setCarouselPosts(posts);
    });
  }, []);

  useEffect(() => {
    setPageNum(1);
    fetchPosts(true);
  }, [activeModule]);

  const fetchPosts = async (reset = false) => {
    const section = sectionMap[activeModule];
    try {
      const res = await service.get(`/forum2/sections/${section}/posts`, {
        params: {
          pageNum: reset ? 1 : pageNum,
          pageSize,
        },
      });
      const records = res?.records || [];
      const total = res?.total || 0;

      if (reset) {
        setPosts(records);
        setPageNum(2);
      } else {
        setPosts((prev) => [...prev, ...records]);
        setPageNum((prev) => prev + 1);
      }

      if ((reset ? records.length : posts.length + records.length) >= total) {
        setHasMore(false);
      } else {
        setHasMore(true);
      }
    } catch (error) {
      console.error("加载帖子失败", error);
    }
  };

  const loadMorePosts = () => {
    fetchPosts();
  };

  const WatchMessage = (index) => {
    navigate(`/postdetail/${index}`);
  };

  // 搜索帖子加载
  const fetchSearchPosts = async (reset = false) => {
    if (!searchKeyword.trim()) {
      // 空关键词时重置搜索
      setIsSearching(false);
      return;
    }
    try {
      const res = await service.get("/forum2/posts/search", {
        params: {
          pageNum: reset ? 1 : pageNum,
          pageSize,
          keyword: searchKeyword.trim(),
        },
      });
      console.log(res,searchKeyword)
      const records = res?.records || [];
      const total = res?.total || 0;

      if (reset) {
        setPosts(records);
        setPageNum(2);
      } else {
        setPosts((prev) => [...prev, ...records]);
        setPageNum((prev) => prev + 1);
      }

      if ((reset ? records.length : posts.length + records.length) >= total) {
        setHasMore(false);
      } else {
        setHasMore(true);
      }
    } catch (error) {
      console.error("搜索帖子失败", error);
    }
  };

  const onSearchClick = () => {
    if (searchKeyword.trim()) {
      setIsSearching(true);
      setPageNum(1);
      fetchSearchPosts(true);
    } else {
      // 清空搜索，回到分类浏览
      setIsSearching(false);
      setPageNum(1);
      fetchPosts(true);
    }
  };

  return (
    <div style={{ padding: "20px", maxWidth: 1200, margin: "auto" }}>
      {/* 顶部模块切换 */}
      <Tabs defaultActiveKey="图书" onChange={setActiveModule} centered>
        {["图书", "交友", "软件", "音乐", "影视"].map((key) => (
          <TabPane tab={key} key={key} />
        ))}
      </Tabs>

      {/* 上部内容区域 */}
      <Row gutter={24}>
        {/* 左：轮播图 */}
        <Col span={16}>
          <Carousel autoplay>
            {carouselPosts.map((post, index) => (
              <div
                key={index}
                onClick={() => {
                  WatchMessage(post.postId);
                }}
              >
                <div
                  style={{
                    height: 300,
                    cursor: "pointer",
                    borderRadius: 8,
                    width: "100%",
                    background: "#333",
                    color: "#fff",
                    padding: "20px",
                    backgroundImage: `url(${
                      carouselImages[index % carouselImages.length]
                    })`,
                    backgroundSize: "cover",
                    backgroundPosition: "center",
                    position: "relative",
                  }}
                >
                  <div
                    style={{
                      background: "rgba(0, 0, 0, 0.5)",
                      padding: "10px 20px",
                      borderRadius: "8px",
                      position: "absolute",
                      bottom: "20px",
                      left: "20px",
                    }}
                  >
                    <h3 style={{ margin: 0 }}>{post.title}</h3>
                    <p style={{ margin: "5px 0 0", fontSize: 12 }}>
                      作者：{post.username}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </Carousel>
        </Col>

        {/* 右：发帖、搜索、通知 */}
        <Col span={8}>
          <div
            style={{
              padding: 20,
              background: "#fafafa",
              borderRadius: 8,
              boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
              marginBottom: 16,
            }}
          >
            <div style={{ display: "flex" }}>
              <Input
                placeholder="搜索帖子..."
                enterButton
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
              />
              <Button
                type="primary"
                style={{
                  marginLeft: "10px",
                }}
                onClick={() => {
                  onSearchClick();
                }}
              >
                搜索
              </Button>
            </div>
            <Button
              type="primary"
              style={{ marginTop: 10, width: "100%" }}
              onClick={() => navigate("/forum/post")}
            >
              ✍️ 发帖
            </Button>
          </div>
          <div
            style={{
              padding: 20,
              background: "#fafafa",
              borderRadius: 8,
              boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
            }}
          >
            <h4 style={{ marginBottom: 10 }}>📢 通知</h4>
            <List
              size="small"
              dataSource={["系统维护", "新功能上线", "论坛规则更新"]}
              renderItem={(item) => (
                <List.Item>
                  <Badge dot>{item}</Badge>
                </List.Item>
              )}
            />
          </div>
        </Col>
      </Row>

      {/* 帖子列表区域 */}
      <InfiniteScroll
        dataLength={posts.length}
        next={loadMorePosts}
        hasMore={hasMore}
        loader={
          <h4 style={{ textAlign: "center", marginTop: 20 }}>加载中...</h4>
        }
        endMessage={
          <p style={{ textAlign: "center", marginTop: 20, color: "#888" }}>
            没有更多帖子了
          </p>
        }
      >
        <Row gutter={[16, 16]} style={{ marginTop: 30 }}>
          {posts.map((post, index) => (
            <Col span={8} key={index}>
              <Card
                hoverable
                style={{
                  borderRadius: 10,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
                  transition: "0.3s",
                  height: "100%",
                }}
                bodyStyle={{ minHeight: 100 }}
                onClick={() => {
                  console.log(post, index);
                  WatchMessage(post.postId);
                }}
              >
                <Card.Meta
                  title={post.title}
                  description={
                    <div style={{ marginTop: 10 }}>
                      作者：{post.username}
                      <br />
                      发布时间：
                      {new Date(post.createdAt).toLocaleString()}
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </InfiniteScroll>
    </div>
  );
};

export default QuestionList;
